package com.seal.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.seal.comm.utils.Page;
import com.seal.dao.BaseDaoImpl;
import com.seal.dao.IAgentInfoDao;
import com.seal.dto.AgentInfoDto;
import com.seal.model.AgentInfo;

@Repository("agentInfoDaoImpl")
public class AgentInfoDaoImpl extends BaseDaoImpl implements IAgentInfoDao {

	public void addAgentInfo(AgentInfo ca) throws Exception {
		this.save(ca);
	}

	public void updateAgentInfo(AgentInfo ca) throws Exception {
		this.update(ca);
	}

	public void deleteAgentInfo(AgentInfo ca) throws Exception {
		this.delete(ca);
	}

	public AgentInfo getAgentInfoById(Long id) throws Exception {
		return (AgentInfo) this.select(AgentInfo.class, id);
	}

	public List<AgentInfo> getAllAgentInfo(AgentInfoDto dto, Page page)
			throws Exception {
		StringBuffer hql = new StringBuffer("from AgentInfo t where 1=1");

		if (null != dto.getType() && !"".equals(dto.getType())) {
			hql.append(" and t.type = :type");
		}

		if (null != dto.getLang()) {
			hql.append(" and t.lang = :lang");
		}

		if (null != dto.getCompanyName()
				&& !"".equals(dto.getCompanyName())) {
			hql.append(" and t.companyName like :companyName");
		}
		//hql.append(" order by orderNum asc");

		Query query = this.getSession().createQuery(hql.toString());
		query.setProperties(dto);
		if (null != page) {
			query.setFirstResult(page.getFirstResult());
			query.setMaxResults(page.getPageSize());
			String countSql = "select count(t) " + hql.toString();

			Query queryCount = this.getSession().createQuery(countSql);
			queryCount.setProperties(dto);
			page.setTotalNumber(Integer.parseInt(queryCount.uniqueResult()
					.toString()));
		}

		return query.list();
	}
}
